document.addEventListener('DOMContentLoaded', function() {
  const toggleBlurBtn = document.getElementById('toggleBlur');
  const stopBlurBtn = document.getElementById('stopBlur');
  const testConnectionBtn = document.getElementById('testConnection');
  const blurIntensitySelect = document.getElementById('blurIntensity');
  const slideIntervalInput = document.getElementById('slideInterval');
  const backgroundStyleSelect = document.getElementById('backgroundStyle');

  // 加载保存的设置
  loadSettings();

  // 检查当前状态
  checkCurrentState();

  // 事件监听器
  toggleBlurBtn.addEventListener('click', function() {
    // 确保切换间隔不小于5秒
    let interval = parseInt(slideIntervalInput.value);
    if (interval < 5) {
      interval = 5;
      slideIntervalInput.value = 5;
      showStatus('切换间隔已调整为最小值5秒', 'info');
    }
    
    const settings = {
      blurIntensity: blurIntensitySelect.value,
      slideInterval: interval * 1000, // 转换为毫秒
      backgroundStyle: backgroundStyleSelect.value
    };
    
    console.log('发送屏保启动消息', settings);
    
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (chrome.runtime.lastError) {
        console.error('查询标签页错误:', chrome.runtime.lastError);
        showStatus('错误：无法访问当前标签页', 'error');
        return;
      }
      
      if (!tabs[0]) {
        console.error('未找到活动标签页');
        showStatus('错误：未找到活动标签页', 'error');
        return;
      }
      
      console.log('向标签页发送消息:', tabs[0].id);
      
      // 确保内容脚本已加载，然后发送消息
      ensureContentScriptLoaded(tabs[0].id, function(loaded) {
        if (!loaded) {
          showStatus('内容脚本加载失败，请刷新页面后重试', 'error');
          return;
        }
        
        sendMessageWithRetry(tabs[0].id, {
          action: 'toggleBlur',
          settings: settings
        }, function(response, error) {
          if (error) {
            console.error('发送消息错误:', error);
            showStatus('错误：' + error.message, 'error');
          } else if (response && response.success) {
            console.log('屏保启动成功');
            updateButtonState(true);
            showStatus('屏保已启动', 'success');
          } else {
            console.error('屏保启动失败:', response);
            showStatus('屏保启动失败', 'error');
          }
        });
      });
    });
  });

  stopBlurBtn.addEventListener('click', function() {
    console.log('停止屏保按钮被点击');
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (chrome.runtime.lastError) {
        console.error('查询标签页错误:', chrome.runtime.lastError);
        showStatus('错误：无法访问当前标签页', 'error');
        return;
      }
      
      sendMessageWithRetry(tabs[0].id, {action: 'stopBlur'}, function(response, error) {
        if (error) {
          console.error('发送停止消息错误:', error);
          showStatus('错误：' + error.message, 'error');
        } else if (response && response.success) {
          console.log('屏保停止成功');
          updateButtonState(false);
          showStatus('屏保已停止', 'success');
        } else {
          console.error('屏保停止失败:', response);
          showStatus('屏保停止失败', 'error');
        }
      });
    });
  });

  // 测试连接按钮
  testConnectionBtn.addEventListener('click', function() {
    console.log('测试连接按钮被点击');
    showStatus('正在测试连接...', 'info');
    
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (chrome.runtime.lastError) {
        console.error('查询标签页错误:', chrome.runtime.lastError);
        showStatus('错误：无法访问当前标签页', 'error');
        return;
      }
      
      if (!tabs[0]) {
        showStatus('错误：未找到活动标签页', 'error');
        return;
      }
      
      console.log('当前标签页:', tabs[0].url);
      
      // 检查是否是受限制的页面
      if (tabs[0].url.startsWith('chrome://') || tabs[0].url.startsWith('chrome-extension://')) {
        showStatus('当前页面不支持插件功能', 'error');
        return;
      }
      
      ensureContentScriptLoaded(tabs[0].id, function(loaded) {
        if (loaded) {
          console.log('连接测试成功');
          showStatus('连接正常！内容脚本运行中', 'success');
        } else {
          console.error('连接测试失败');
          showStatus('连接失败：内容脚本无法加载', 'error');
        }
      });
    });
  });

  // 保存设置
  function saveSettings() {
    // 确保切换间隔不小于5秒
    let interval = parseInt(slideIntervalInput.value);
    if (interval < 5) {
      interval = 5;
      slideIntervalInput.value = 5;
      showStatus('切换间隔已调整为最小值5秒', 'info');
    }
    
    const settings = {
      blurIntensity: blurIntensitySelect.value,
      slideInterval: interval * 1000, // 转换为毫秒存储
      backgroundStyle: backgroundStyleSelect.value
    };
    chrome.storage.sync.set({screenSaverSettings: settings});
  }

  // 加载设置
  function loadSettings() {
    chrome.storage.sync.get(['screenSaverSettings'], function(result) {
      if (result.screenSaverSettings) {
        const settings = result.screenSaverSettings;
        blurIntensitySelect.value = settings.blurIntensity || '10';
        
        // 确保加载的切换间隔不小于5秒
        let loadedInterval = settings.slideInterval / 1000 || 5;
        if (loadedInterval < 5) {
          loadedInterval = 5;
        }
        slideIntervalInput.value = loadedInterval;
        
        backgroundStyleSelect.value = settings.backgroundStyle || 'images';
      }
    });
  }

  // 检查当前状态
  function checkCurrentState() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (chrome.runtime.lastError || !tabs[0]) {
        return;
      }
      
      // 检查是否是受限制的页面
      if (tabs[0].url.startsWith('chrome://') || tabs[0].url.startsWith('chrome-extension://')) {
        return;
      }
      
      sendMessageWithRetry(tabs[0].id, {action: 'getState'}, function(response) {
        if (response && response.isActive) {
          updateButtonState(true);
        }
      });
    });
  }

  // 更新按钮状态
  function updateButtonState(isActive) {
    if (isActive) {
      toggleBlurBtn.style.display = 'none';
      stopBlurBtn.style.display = 'block';
    } else {
      toggleBlurBtn.style.display = 'block';
      stopBlurBtn.style.display = 'none';
    }
  }

  // 设置变化时保存
  blurIntensitySelect.addEventListener('change', saveSettings);
  slideIntervalInput.addEventListener('change', saveSettings);
  backgroundStyleSelect.addEventListener('change', saveSettings);

  // 带重试机制的消息发送函数
  function sendMessageWithRetry(tabId, message, callback, maxRetries = 3, delay = 200) {
    let attempts = 0;
    
    function attemptSend() {
      attempts++;
      chrome.tabs.sendMessage(tabId, message, function(response) {
        if (chrome.runtime.lastError) {
          console.log(`消息发送尝试 ${attempts}/${maxRetries} 失败:`, chrome.runtime.lastError.message);
          
          if (attempts < maxRetries && 
              chrome.runtime.lastError.message.includes('Could not establish connection')) {
            // 如果是连接错误且还有重试次数，则延迟后重试
            setTimeout(attemptSend, delay * attempts);
          } else {
            // 达到最大重试次数或其他错误，调用回调
            if (callback) callback(null, chrome.runtime.lastError);
          }
        } else {
          // 成功，调用回调
          if (callback) callback(response);
        }
      });
    }
    
    attemptSend();
  }

  // 检查内容脚本是否已加载
  function ensureContentScriptLoaded(tabId, callback) {
    sendMessageWithRetry(tabId, {action: 'ping'}, function(response, error) {
      if (response && response.success) {
        callback(true);
      } else {
        console.log('内容脚本未加载，尝试注入...');
        // 尝试重新注入内容脚本
        chrome.scripting.executeScript({
          target: { tabId: tabId },
          files: ['content.js']
        }, function() {
          if (chrome.runtime.lastError) {
            console.error('注入内容脚本失败:', chrome.runtime.lastError);
            callback(false);
          } else {
            // 等待一下再检查
            setTimeout(() => {
              sendMessageWithRetry(tabId, {action: 'ping'}, function(response) {
                callback(response && response.success);
              }, 1);
            }, 500);
          }
        });
      }
    }, 1); // 只尝试一次ping
  }

  // 显示状态信息
  function showStatus(message, type = 'info') {
    // 移除已存在的状态提示
    const existingStatus = document.getElementById('status-message');
    if (existingStatus) {
      existingStatus.remove();
    }
    
    const statusDiv = document.createElement('div');
    statusDiv.id = 'status-message';
    statusDiv.textContent = message;
    statusDiv.style.cssText = `
      margin-top: 10px;
      padding: 8px 12px;
      border-radius: 4px;
      font-size: 12px;
      text-align: center;
      background: ${type === 'error' ? '#ff4444' : type === 'success' ? '#44aa44' : '#4488aa'};
      color: white;
      opacity: 0.9;
    `;
    
    document.body.appendChild(statusDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
      if (statusDiv && statusDiv.parentNode) {
        statusDiv.remove();
      }
    }, 3000);
  }
}); 